package com.kuangstudy.thread.advanced;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Losca
 * @date 2021/7/22 13:56
 * 测试lock锁
 */
public class Demo1 {
    public static void main(String[] args) {
        Lock2 lock2 = new Lock2();
        new Thread(lock2).start();
        new Thread(lock2).start();
        new Thread(lock2).start();
        /**
         * 10
         * 9
         * 8
         * 7
         * 6
         * 5
         * 4
         * 3
         * 2
         * 1
         */
    }

}

class Lock2 implements Runnable {
    int ticket = 10;
    //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();//加锁
                if (ticket > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticket--);
                }else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            //解锁
                lock.unlock();
            }
        }

    }
}
